import axios, { AxiosError, type AxiosResponse } from "axios";
import { useUserInfoStore } from "@/stores/userInfo";
import { showFailToast } from "vant";

const instance = axios.create({
    baseURL: 'https://geek.itheima.net/',
    timeout: 6000
})

instance.interceptors.request.use((config) => {
    const store = useUserInfoStore()
    const token = store.token
    config.headers["Content-Type"] = 'application/json'
    config.headers.Authorization = "Bearer " + token
    return config
}, (error: AxiosError) => {
    alert("千古一遇：" + error)
    return Promise.reject(error)
})

instance.interceptors.response.use((resp: AxiosResponse) => {
    return resp
}, (error: AxiosError) => {
    if(error.response?.status === 401) {
        showFailToast({message: "登录超时"})
        return Promise.reject(error)
    }
    const res = error.response?.data as IRes
    showFailToast(res.message)
    return Promise.reject(error)
})

export const RequestAxios = <T>(config: object) => {
    return instance<null, AxiosResponse<T>, null>(config)
}